import type { MiddlewareFactory, Route } from 'router5/dist/types/router';
import type { RouterDependencies } from '../interfaces';
import type { Router } from 'router5';
import { findSegment } from '../index';

interface IAuthGuard {
  fallbackRoute: string;
  auth: boolean;
}

export interface IAuthGuardMiddlewareConfig {
  auth?: (router: Router<RouterDependencies>) => IAuthGuard;
}

export const authGuardMiddlewareFactory =
  (
    routes: Route<RouterDependencies>[],
  ): MiddlewareFactory<RouterDependencies> =>
  (router) =>
  (toState, _fromState, done): void => {
    const segment = findSegment(toState.name, routes);

    if (segment && (segment as any).auth) {
      const authResult = (segment as any).auth(router) as IAuthGuard;

      if (authResult.auth) {
        done();
        return;
      }

      done({
        redirect: {
          name: authResult.fallbackRoute,
        },
      });
      return;
    }
    done();
  };
